<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .result-box{
      text-align: center; box-shadow: 0 5px 8px #ddd; border: 1px solid #ddd; 
      width: 300px; border-radius: 5px; padding: 10px;
    }
  </style>
  <script src="./js/jquery-2.1.1.min.js"></script>
  <script src="./js/vue.min.js"></script>
  <script src="https://sf3-cn.feishucdn.com/obj/static/lark/passport/qrcode/LarkSSOSDKWebQRCode-1.0.1.js"></script>
</head>

<body>
  <div id="app">
    <h1>飞书扫码登录--第三方授权登录</h1>
    <hr />

    <div id="login_container"></div>

    <div v-if="userInfo.picture" class="result-box">
      <div>
        <img v-if="userInfo.picture" :src="userInfo.picture" width="60px" />
      </div>
      <p>{{userInfo.name}}</p>
      <p>登录成功！</p>
    </div>

  </div>

  <script>
    var vm = new Vue({
      el: "#app",
      data: {
        userInfo: {
          picture: "",
          name: 'sdf'
        }
      }
    })
    // 飞书官方文档 https://open.feishu.cn/document/common-capabilities/sso/web-application-sso/qr-sdk-documentation

    // 配置数据
    var backUrl = "http://a667-223-104-63-37.ngrok.io/html"
    var config = {
      client_id: "cli_a2dc74533c78500d",
      client_secret: "Otm3Rk0hJGMpwO2lLOgh5e0rIrx7epHh",
      redirect_uri: backUrl
    }
    let origin = window.location.origin



    function get_userinfo(access_token) {
      let url = "https://passport.feishu.cn/suite/passport/oauth/userinfo"
      $.ajax({
        type: "get",
        url,
        cache: false,
        async: true,
        beforeSend: function (XHR) {
          // 功能：添加自定义 HTTP 头 Authorization。
          XHR.setRequestHeader("Authorization", `Bearer ${access_token}`);
        },
        dataType: 'json',
        // dataType: ($.browser.msie) ? "text" : "xml",
        success: function (data) {
          console.log('get_userinfo-成功--', data);
        },
        fail: function (err) {
          console.log('get_userinfo-err--', err);
        }
      })

    }

    function getToken(form) {
      let url = origin + "/getfsToken"
      $.ajax({
        type: "post",
        url,
        data: form,
        cache: false,
        async: true,
        beforeSend: function () {
          //等待延迟的函数
        },
        dataType: 'json',
        // dataType: ($.browser.msie) ? "text" : "xml",
        success: function (data) {
          console.log('getfsToken-成功--', data);
          // 更新页面数据
          vm.$data.userInfo.picture = data.picture;
          vm.$data.userInfo.name = data.name;

          // get_userinfo(data.access_token) // 前端访问会跨域，还是需要通过后台访问
        },
        fail: function (err) {
          console.log('getfsToken-err--', err);
        }
      })

    }

    // 获取url的参数
    function getUrlParams() {
      let str = window.location.search
      console.log('str', str);
      // ?code=051YCH000vmCDN1EmM200Bdl0f3YCH0w:77 str ?
      if (str && str.includes("?") && str.includes("=")) {
        let obj = {}
        str = str.slice(1)
        console.log('str', str);
        if (str.includes("&")) {
          let arr = str.split("&")
          console.log('arr', arr);
          for (let i = 0; i < arr.length; i++) {
            let one = arr[i].split("=")
            obj[one[0]] = one[1]
          }
        } else {
          let one = str.split("=")
          obj[one[0]] = one[1]
        }
        return obj;
      }
    }


    window.onload = () => {
      let params = getUrlParams()
      console.log('params', params);
      if (params && params.code) {

        // 获取token https://open.feishu.cn/document/common-capabilities/sso/api/get-access_token
        let form = {
          grant_type: "authorization_code",
          client_id: config.client_id,
          client_secret: config.client_secret,
          code: params.code,
          redirect_uri: config.redirect_uri

        }
        getToken(form)

        return
      }

      console.log("-------调起扫码----")


      // 调起扫码
      var goto = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${config.client_id}&redirect_uri=${config.redirect_uri}&response_type=code&state=state123456`;

      // 利用前端网页跳转
      // window.location.href = url;

      var QRLoginObj = QRLogin({
        id: "login_container",
        goto,
        // goto: "https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=cli_a03f23493d39d00e&redirect_uri=https%3A%2F%2Fwww.baidu.com&response_type=code&state=STATE",
        width: "300",
        height: "300",
      });
      var handleMessage = function (event) {
        console.error('event', event);
        var origin = event.origin;
        // 使用 matchOrigin 方法来判断 message 是否来自飞书页面
        if (QRLoginObj.matchOrigin(origin)) {
          var loginTmpCode = event.data;
          // 在授权页面地址上拼接上参数 tmp_code，并跳转
          window.location.href = `${goto}&tmp_code=${loginTmpCode}`;
          console.log(loginTmpCode)
        }
      };
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
      }
      else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage);
      }
      // 原文链接：https://blog.csdn.net/xutongbao/article/details/123278795
    }



  </script>

</body>

</html>